import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/* eslint-disable react/jsx-no-undef */
import React from "react";
import { DevNotify } from "~/public/cpas-ui/index";
import { defaultCellStyle, } from "./HandSonGrid";
import { Modal, message } from "antd";
import DevDefaultPopup from "~/public/cpas-ui/components-ui/express-components/DevPopup";
import _ from "lodash";
import { Select } from "antd";
import { ExportToExcel, ImportExcel, ExportToDraft, } from "./classes/ExcelService";
import { Autocomplete } from "devextreme-react/autocomplete";
import HandsonTabHeader from "./components/MenuTool/HandsonTabHeader";
import GetDataAndValidator from "./components/MenuTool/GetDataAndValidator";
import TableEditorService from "./classes/HandSonGridToolService/TableEditorService";
import RowEditorService from "./classes/HandSonGridToolService/RowEditorService";
import ColumnEditorService from "./classes/HandSonGridToolService/ColumnEditorService";
import HandsonTableHeaderService from "./classes/HandSonGridToolService/HandsonTableHeaderService";
import CollationModeService from "./classes/HandSonGridToolService/CollationModeService";
import LogicPopup from "~/public/cpas-ui/components-bs/LogicPopup/index";
import LogicFormulaService from "./classes/LogicFormulaService";
import Draggable from "react-draggable"; // 此代码不要给我再删除，它是让弹窗可以移动，没有包可以安装依赖包
import ColData from "./components/MenuTool/colData";
import RowData from "./components/MenuTool/rowData";
import ReductionEditor from "./components/MenuTool/ReductionEditor";
import { resetSessionDismantleData } from "./components/MenuTool/ReductionEditor";
import { getDsToZlData, parseLogicFormulaData } from "./api/DesignTableApi";
import { consts } from "../../tools/consts";
import { getExpandTableColumns } from "./Tools";
import { msgError } from "./components/MenuTool/msg";
import Editor from "./components/MenuTool/Editor";
import CellDataV2 from "./components/MenuTool/cellData/CellDataV2";
import { getCurrentSysName, SystemName, MergeType, getHbTypeByZcbfid, } from "../../tools/Tools";
const { Option } = Select;
let wantDeleteFatherKeys = [];
export default class HandSonGridTool extends React.PureComponent {
    gridRef;
    tableEditorService;
    rowEditorService;
    columnEditorService;
    handsonTableHeaderService;
    collationModeService;
    get headerService() {
        return this.gridRef.headerService;
    }
    get gridService() {
        return this.gridRef.gridService;
    }
    get hot() {
        return this.gridRef.gridService.hot;
    }
    get hyper() {
        return this.gridRef.hyper;
    }
    get formulaService() {
        return this.gridRef.formulaService;
    }
    get tagService() {
        return this.gridRef.tagService;
    }
    buttonDropDownOptions = { width: 150 };
    //分组后的组头位置信息
    currentGroupInfo;
    tabsRef;
    batchInsertPopup;
    menuToolNotifyRef;
    rowRef;
    colRef;
    cellRef;
    tableToolsRef;
    reductionEditorRef;
    tableDesignToolRef;
    //excel函数
    ExportToExcel;
    ImportExcel;
    ExportToDraft;
    //标签输入框
    tagInputRef = React.createRef();
    //计算单个文字宽度的内容
    textCanvasRef = React.createRef();
    draftPopupRef = React.createRef();
    insertRows = [
        { id: 1, name: "单元格取数" },
        { id: 2, name: "列动态取数" },
        { id: 3, name: "行动态取数" },
    ];
    zhengli = [
        { id: 1, name: "横向" },
        { id: 2, name: "纵向" },
    ];
    yanJingYinCang = [
        { id: 1, name: "项目" },
        { id: 2, name: "期末余额" },
        { id: 3, name: "期初余额" },
    ];
    indentation = [
        { id: 1, name: "首行缩进" },
        { id: 2, name: "整行缩进" },
    ];
    insertColumnOptions = [
        { id: 1, name: "在右方插入", icon: "iconfont icon-zaiyoucharulie" },
        { id: 2, name: "在左方插入", icon: "iconfont icon-zaizuocharulie" },
        { id: 3, name: "插入子列", icon: "iconfont icon-lie" },
    ];
    insertRowsOptions = [
        { id: 1, name: "在下方插入", icon: "iconfont icon-zaixiafangcharuhang" },
        { id: 2, name: "在上方插入", icon: "iconfont icon-zaishangfangcharuhang" },
        { id: 3, name: "插入指定行数", icon: "iconfont icon-hang" },
    ];
    //运算公式数据源->后期扩展成api读取   currentOperationalFormula: string;  //当前运算公式
    operationalFormulaOptions = ['=CP_CELL("","","","")', '=FS_CELL("","","")'];
    //TODO 输入公式做联想提示
    // dataSource = new DataSource({
    //   store: ['CP_CELL("","","","")', 'FS_CELL("","","")'],
    //   // filter: ["birthYear", "<", 2000],
    //   searchOperation: "notcontains",
    //   searchExpr: function (dataItem) {
    //     return dataItem.firstName + " " + dataItem.lastName;
    //   },
    //   onChanged: function (value) {
    //     console.log(value);
    //     return value;
    //   },
    // });
    dateAndTimeTypeOption = [
        { id: 1, name: "" },
        { id: 2, name: "时间点" },
        { id: 3, name: "时间段" },
    ];
    columnTypeOption = [
        { id: "numeric", name: "数值" },
        { id: "text", name: "文本" },
        { id: "percent", name: "百分比" },
    ];
    exportOption = [
        { id: 1, name: "导出Json文件" },
        { id: 2, name: "导出Excel文件" },
    ];
    importOption = [
        { id: 1, name: "导入Json文件" },
        { id: 2, name: "导入Excel文件" },
    ];
    simpleProducts = [
        "文本拼接",
        "时间点",
        "SuperPlasma 50",
        "SuperLED 50",
        "SuperLED 42",
        "SuperLCD 55",
        "SuperLCD 42",
        "SuperPlasma 65",
        "SuperLCD 70",
        "Projector Plus",
        "Projector PlusHT",
        "ExcelRemote IR",
        "ExcelRemote BT",
        "ExcelRemote IP",
    ];
    zixingData = [
        { id: 1, name: "常规" },
        { id: 2, name: "倾斜" },
    ];
    zihaoData = [
        { id: "small4", name: "小4" },
        { id: "small5", name: "小5" },
    ];
    zitiColorData = [
        { id: "black", name: "黑色" },
        { id: "red", name: "红色" },
    ];
    // 列聚合选项
    columnAggregationOption = [
        { id: "SUM", name: "求和" },
        { id: "AVERAGE", name: "平均" },
        //{ id: "COUNT", name: "计数" },
        { id: "MAX", name: "最大" },
        { id: "MIN", name: "最小" },
        { id: "CLEAR", name: "清空" },
        //{ id: "textConcat", name: "文本拼接" },
    ];
    rowAggregationOption = [
        { id: "SUM", name: "求和" },
        { id: "AVERAGE", name: "平均" },
        //{ id: "COUNT", name: "计数" },
        { id: "MAX", name: "最大" },
        { id: "MIN", name: "最小" },
        { id: "CLEAR", name: "清空" },
        //{ id: "textConcat", name: "文本拼接" },
    ];
    qiJianTypeOption = [
        { id: "none", name: "无" },
        { id: "pt", name: "时间点" },
        { id: "pd", name: "时间段" },
    ];
    juHeFangShiData = [
        { id: "SUM", name: "求和" },
        { id: "AVERAGE", name: "平均" },
        { id: "COUNT", name: "计数" },
        { id: "MAX", name: "最大" },
        { id: "MIN", name: "最小" },
    ];
    customOperationData = [
        { id: "j", label: "减", value: "j" },
        { id: "z", label: "中", value: "z" },
        { id: "a", label: "加", value: "a" },
    ];
    hideColumnArr = []; // 存隐藏列的下标
    hideColumnKeyArr = []; // 存隐藏列的key
    needReverseGroupInfo; // 需要逆序的列信息
    /**
     * 解析tableConfig 并更新工具条
     * @param hideColumnArr
     */
    updateTableConfigToolsState(tableConfig) {
        this.refreshMenuToolState();
    }
    hideColumn = (hideColumnArr) => {
        this.hot.updateSettings({
            nestedHeaders: this.headerService.data,
            hiddenColumns: {
                columns: [0, this.headerService.lastHeader, ...hideColumnArr],
            },
            hiddenRows: {
                rows: [0],
            },
        });
    };
    onProjectChange = async (item, e) => {
        let hideColumnKeyArr = this.gridRef.tableConfig.hideColumnKeyArr || [];
        let hideColumnArr = this.gridRef.tableConfig.hideColumnArr || [];
        // let dismantleTableMode;
        // if (sessionStorage.dismantleTableMode) {
        //   dismantleTableMode = JSON.parse(sessionStorage.dismantleTableMode);
        // }
        const checked = e.target.checked; // 获取是否选中这个下拉框
        const hiddenItemKey = item.key; // 得到隐藏列的key
        const columnArr = this.headerService.getVisibleColumn(); // 得到所有隐藏列
        let hiddenColumnIndex = -1; // 计算实际隐藏列的下标
        // 根据隐藏列的key 再去 columnArr 找这个列现在的下标（因为有移动列的情况）
        for (let i = 0; i < columnArr?.length; i++) {
            if (columnArr[i].key === hiddenItemKey) {
                hiddenColumnIndex = i + 1;
            }
        }
        // if (dismantleTableMode) {
        //   hideColumnArr = sessionStorage.hideColumnArr
        //     ? JSON.parse(sessionStorage.hideColumnArr)
        //     : [];
        //   hideColumnKeyArr = sessionStorage.hideColumnKeyArr
        //     ? JSON.parse(sessionStorage.hideColumnKeyArr)
        //     : [];
        // }
        if (checked) {
            // 选中添加隐藏列
            hideColumnArr.push(hiddenColumnIndex);
            hideColumnKeyArr.push(hiddenItemKey);
            // hideColumnKeyArr = ['e4b438d3d69e48c8baf27329ff7643c4', '5a266e452af14dbc971ab8a1705cc0a9']; // 3 4列隐藏
        }
        else {
            // 未选中移除隐藏列
            hideColumnArr = hideColumnArr.filter((item) => item != hiddenColumnIndex);
            hideColumnKeyArr = hideColumnKeyArr.filter((item) => item != hiddenItemKey);
        }
        this.gridRef.tableConfig.hideColumnArr = hideColumnArr;
        this.gridRef.tableConfig.hideColumnKeyArr = hideColumnKeyArr;
        let rule = this.gridRef.tableConfig.rule;
        if (rule) {
            this.gridRef.tableConfig.rule = rule;
        }
        else {
            // 处理用户导入json文件时，恢复拆表后，点击隐藏仍然拆表的问题
            delete this.gridRef.tableConfig.rule;
            delete this.gridRef.tableConfig.dismantleTableMode;
        }
        const headerData = this.gridRef.headerData;
        const tableData = this.gridRef.data;
        const cellsMeta = this.gridRef.cellMetaData;
        const tableConfig = this.gridRef.tableConfig;
        let souceData = {
            header: headerData,
            data: tableData,
            cellsMeta,
            tableConfig,
        };
        // 日志埋点
        this.gridRef.setTableContentChange(true, {
            type: "隐藏",
            params: {
                ...this.gridRef.tableConfig,
            },
        });
        const dsFormulaSourceData = this.gridRef.props.dsTableRef.getFormulaSourceData();
        const tid = this?.gridRef?.props?.notes?.tid;
        const result = await getDsToZlData(this.gridRef.dsSourceData, this.gridRef.tableConfig, dsFormulaSourceData, tid);
        if (result && result.data) {
            const resultData = result.data;
            const { zlGridData, zlDivideData } = resultData;
            await this.gridRef.reloadTable(zlGridData, "zl", this.gridRef.dsSourceData);
            const refs = this.gridRef.afterDivideTableRender(zlDivideData);
            //更新整理模式下cpastable实例
            this.gridRef && this.gridRef?.dsTableRef?.setZlCpasTableRefs(refs);
        }
        // 拆表后还可以隐藏
        // sessionStorage.hideColumnArr = JSON.stringify(hideColumnArr);
        // sessionStorage.hideColumnKeyArr = JSON.stringify(hideColumnKeyArr); // 拆表后再隐藏 原来的 HandsonTable 实例销毁了 所以要把隐藏列存起来
    };
    removeHeader = (headerData, hideColumnKeyArr, fatherNode) => {
        for (let i = 0; i < headerData.length; i++) {
            let isDelete = false;
            const headerDataItem = headerData[i];
            if (hideColumnKeyArr.includes(headerDataItem.key)) {
                const deletedObjArr = headerData.splice(i, 1); //
                const deleteObjKey = deletedObjArr[0].key;
                // 删完后从待删除数组中移除该元素
                wantDeleteFatherKeys = wantDeleteFatherKeys.filter((item) => item !== deleteObjKey);
                isDelete = true;
                if (headerData.length === 0) {
                    // 子元素数组删空了 同时删除父元素
                    wantDeleteFatherKeys.push(fatherNode.key);
                }
            }
            else if (headerDataItem.children &&
                headerDataItem.children.length > 0) {
                // 复合列
                const children = headerDataItem.children;
                this.removeHeader(children, hideColumnKeyArr, headerDataItem);
            }
            if (!isDelete) {
                // 因为删除数组元素后，数组长度变了，如果i再加1的话 会少遍历一个元素，所以当删除元素时i不能加1
                i++;
            }
        }
    };
    hideColumns = async (sourceData, hideColumnKeyArr, hideColumnArr) => {
        const headerData = sourceData.header;
        //一. 去headerData 中把对应的 key 的节点移除
        this.removeHeader(headerData, hideColumnKeyArr);
        while (wantDeleteFatherKeys.length > 0) {
            this.removeHeader(headerData, wantDeleteFatherKeys);
        }
        //二. 去data中把对应的列数据删除
        // 1. 获取隐藏列的下标
        let hideColumnDataIndexArr = hideColumnArr;
        // 2. 把对应下标的data删除
        const tableData = sourceData.data;
        for (let i = 0; i < tableData.length; i++) {
            let tableRowData = tableData[i];
            tableRowData = tableRowData.filter((item, index) => !hideColumnDataIndexArr?.includes(index));
            tableData[i] = tableRowData;
        }
        // 三. 修改 cellMetaData
        //1. 删除隐藏的单元格样式对象
        const cellMetaData = sourceData.cellsMeta;
        for (let j = 0; j < hideColumnDataIndexArr?.length; j++) {
            const hidenColumnIndex = hideColumnDataIndexArr?.[j];
            // 1.删除隐藏列的cellMeta对象
            for (let i = 0; i < cellMetaData.length; i++) {
                const cellMetaItem = cellMetaData[i];
                if (cellMetaItem.col === hidenColumnIndex) {
                    cellMetaData.splice(i, 1);
                }
            }
        }
        //2. 修改col的值
        for (let i = 0; i < cellMetaData.length; i++) {
            const cellMetaItem = cellMetaData[i];
            //计算向左移动几个
            let move = 0;
            for (let j = 0; j < hideColumnDataIndexArr.length; j++) {
                const hideColumnDataIndex = hideColumnDataIndexArr[j]; // 3
                if (cellMetaItem.col > hideColumnDataIndex) {
                    move++;
                }
            }
            cellMetaItem.col = cellMetaItem.col - move;
        }
        // 隐藏完毕以后刷新table
        const igridData = {
            header: headerData,
            data: tableData,
            cellsMeta: cellMetaData,
            tableConfig: this.gridRef.tableConfig,
        };
        return igridData;
    };
    showDividedTable(gridDataArr) {
        const refs = this.reductionEditorRef.current.afterDivideTableRender(gridDataArr);
        //更新整理模式下cpastable实例@todo
        this.gridRef && this.gridRef?.dsTableRef?.setZlCpasTableRefs(refs);
    }
    juHeFangShiChange(e) {
        const currentJuHeFangShi = e.itemData.id;
        this.setState({
            pType: currentJuHeFangShi,
        });
    }
    //行标签聚合下拉框change
    juiheRowChange(e) {
        const currentJuHeRowId = e.itemData.id;
        this.setState({
            rowPType: currentJuHeRowId,
        });
    }
    juheColumnChange(e) {
        const currentJuHeRowId = e.itemData.id;
        console.log(currentJuHeRowId, "currentJuHeRowId");
        this.setState({
            cellPType: currentJuHeRowId,
        });
    }
    rowOperatorChange(e) {
        const isRowOperatorTag = this.state.isRowOperatorTag;
        this.setState({
            isRowOperatorTag: !isRowOperatorTag,
        });
    }
    twoTableTraslation; // 列动态关系回显变量
    rowTableTraslation; // 行动态关系回显变量
    comSoureSelect;
    constructor(props) {
        super(props);
        this.tabsRef = React.createRef();
        this.batchInsertPopup = React.createRef();
        this.menuToolNotifyRef = React.createRef();
        this.gridRef = props.gridRef;
        this.rowRef = React.createRef();
        this.colRef = React.createRef();
        this.cellRef = React.createRef();
        this.tableToolsRef = React.createRef();
        this.reductionEditorRef = React.createRef();
        this.tableDesignToolRef = React.createRef();
        this.state = {
            cellTabsActiveKey: consts.ReportTabKey,
            selectedIndex: 0,
            tabs: [],
            bl: defaultCellStyle.bl,
            it: defaultCellStyle.it,
            r: defaultCellStyle.r,
            ht: 0,
            fc: defaultCellStyle.fc,
            bg: defaultCellStyle.bg,
            headerHt: 0,
            ro: undefined,
            headerBl: 0,
            isOpenSetGroup: false,
            fixedColumnsStart: 0,
            currentColumnName: "",
            currentColumnType: "numeric",
            currentColumnMap: "",
            currentRowMap: "",
            currentColumnAggregation: "sum",
            currentRowAggregation: "sum",
            currentQiJianType: "none",
            pType: "SUM",
            rowPType: "",
            isRowOperatorTag: false,
            cellPType: "",
            tagType: "row",
            pExclude: false,
            cExclude: false,
            //isRowColumnTag: false,
            isOpenSetTag: false,
            isOpenPolymeric: false,
            isOpenCustomOperation: false,
            currentRowTags: [],
            currentColumnTags: [],
            allRowTags: [],
            allColumnTags: [],
            currentSelectedTags: [],
            currentOperationLists: [],
            weightType: "",
            showRowTag: false,
            keyword: [],
            keywordState: false,
            percentFormat: false,
            currentGroupKeyColumn: null,
            currentOperationalFormula: "",
            currentVerifyFormula: '=CP_CELL("未审财务数据","应收账款","QMYE")\n',
            wenziPanelVisible: false,
            currentZiHao: "small4",
            currentZiTiColor: "black",
            isRowPop: false,
            titles: "",
            isRow: false,
            isCol: false,
            isCell: false,
            columnsData: [],
            listData: [],
            cpasData: {},
            saveArr: [],
            yearSel: "",
            selSrc1: "",
            rowSrc2: {},
            oneHeaders: [],
            colIndex: 0,
            coords: {},
            getTraslates: [],
            getWheres: {},
            tabText1: "",
            onReceiveKeywords: () => { },
            isReverse: false,
            ComDataSoureSelect: [],
            digaoNameSelect: [],
            objChild: {},
            top: "",
            ckCol: 0,
            sliderPosition: 0,
            bodyClientWidth: 0,
            cDevCpasMap: [],
            disabled: true,
            bounds: { left: 0, top: 0, bottom: 0, right: 0 },
            dbName: window.sessionStorage.electronParams
                ? JSON.parse(window.sessionStorage.electronParams)?.params?.DBName
                : consts.defaultDbName,
            cellCoords: {},
            itemName: "",
            formulaOff: false,
            formulaMark: false,
            tab: "",
            yearSel1: "",
            yearSel2: "",
            tbName1: "",
            tbName2: "",
            projectName1: "",
            projectName2: "",
            reportItem: "",
            tab1: "",
            tab2: "",
            conditonStr: "",
            existsRowFormula: false,
            isShowForm: false,
            existsColFormula: false,
            isShowColForm: false,
            maskValue: "none", //工具栏的遮罩默认隐藏
        };
        this.onTabsSelectionChanged = this.onTabsSelectionChanged.bind(this);
        this.tableDesignToolsRender = this.tableDesignToolsRender.bind(this);
        this.setCellRetract = this.setCellRetract.bind(this);
        this.setFixedColumnsStart = this.setFixedColumnsStart.bind(this);
        this.insertColumnHandle = this.insertColumnHandle.bind(this);
        this.removeColumnHandle = this.removeColumnHandle.bind(this);
        this.removeRowHandle = this.removeRowHandle.bind(this);
        this.columnNameChange = this.columnNameChange.bind(this);
        this.updateColumnState = this.updateColumnState.bind(this);
        this.columnTypeChange = this.columnTypeChange.bind(this);
        this.save = this.save.bind(this);
        this.onChangeRowMap = this.onChangeRowMap.bind(this);
        this.onChangeColumnMap = this.onChangeColumnMap.bind(this);
        this.selectTagsChange = this.selectTagsChange.bind(this);
        this.setColumnKeyword = this.setColumnKeyword.bind(this);
        this.ExportToExcel = ExportToExcel.bind(this);
        this.ImportExcel = ImportExcel.bind(this);
        this.ExportToDraft = ExportToDraft.bind(this);
        this.operationalFormulaChanged = this.operationalFormulaChanged.bind(this);
        this.verifyFormulaChanged = this.verifyFormulaChanged.bind(this);
        this.formulaChanged = this.formulaChanged.bind(this);
        this.hideWenZiPanel = this.hideWenZiPanel.bind(this);
        this.hideSetTagPanel = this.hideSetTagPanel.bind(this);
        this.hideLabelJuHePanel = this.hideLabelJuHePanel.bind(this);
        this.hideLabelCustomOperation = this.hideLabelCustomOperation.bind(this);
        this.showWenZiPanel = this.showWenZiPanel.bind(this);
        this.generateLogicFormula = this.generateLogicFormula.bind(this);
        this.handleArrowClick = this.handleArrowClick.bind(this);
        this.resizeUpdate = this.resizeUpdate.bind(this);
        this.getrowSrc2event = this.getrowSrc2event.bind(this);
        this.addCustomOperation = this.addCustomOperation.bind(this);
    }
    //是否重新显示
    setIsShowForm = (value) => {
        console.log("888---行 是否重新显示", value);
        this.setState({ isShowForm: value });
    };
    //是否重新显示 - 列
    setIsShowColForm = (value) => {
        console.log("888--列动态是否重新显示", value);
        this.setState({ isShowColForm: value });
    };
    // 取数源设置下拉菜单点击事件 -- 三个弹窗
    onItemClick = async (e) => {
        console.log("888---ceshi-取数设置打开弹窗e", e);
        // 更改于2023.7.13 15:03, 因为 itemName 的值变为了“11，222，33” 这样的格式，现在是取第一个值
        let itemStrName = this.gridRef.props.itemName;
        //单元格取数获取反编译公式
        if (e.itemData.name === "单元格取数") {
            if (this.state.coords.col &&
                this.state.coords.row &&
                this.state.coords.col > 0 &&
                this.state.coords.row > 0) {
                this.gridRef.getFormulaByCoords(this.state.coords, "cell");
            }
            else {
                console.log("清空本地单元格缓存");
                await this.gridRef.hyperFormulaService.clearCache();
                this.setState({
                    isRowPop: true,
                    titles: "单元格取数",
                    isCol: false,
                    isRow: false,
                    isCell: true,
                });
                // return false;
            }
            // 和左边树节点的交互
            if (itemStrName) {
                this.setState({
                    itemName: itemStrName.split(",")[0] || "",
                });
            }
        }
        if (this.gridRef.state.currentRecord == null &&
            e.itemData.name === "行动态取数") {
            message.open({
                type: "info",
                content: "请选择行号",
                className: "custom-class",
                style: {
                    marginTop: "20vh",
                },
            });
        }
        if (this.gridRef.state.currentRecord == null &&
            e.itemData.name === "列动态取数") {
            message.open({
                type: "info",
                content: "请选择列号",
                className: "custom-class",
                style: {
                    marginTop: "20vh",
                },
            });
        }
        if (this.gridRef.state.currentRecord) {
            const coords = this.gridRef.state.currentRecord.coords;
            console.log("888--row-col", coords);
            this.setState({
                cellCoords: coords,
            });
            // this.gridRef.hot.selectCell(coords.row, coords.col);
            if (coords.row === -1 && e.itemData.name === "行动态取数") {
                message.open({
                    type: "warning",
                    content: "当前点击没有选中行号，需要点击行才能进行行动态取数",
                    className: "custom-class",
                    style: {
                        marginTop: "20vh",
                    },
                });
            }
            // 处理两表存储关系的地方
            if (e.itemData.name === "行动态取数" && coords.row !== -1) {
                // 去拿到devtable数据
                const cpasData = this.gridRef.getCpasTableGrid();
                // const new_header2 = this.gridRef.headerService.headerColumn;
                const new_header = []; //平铺的字段,不包含parent
                //把表格的列展开(多表头的列),平铺的字段,不包含children字段,解决多表头的问题
                getExpandTableColumns(new_header, cpasData.header, "");
                /*  //使用数据的第0行为标题
                 if (cpasData.data.length > 0) {
                   let dataRow0 = cpasData.data[0];
                   new_header.forEach((item: any, index: number) => {
                     if (index > 0 && index < new_header.length - 1) {
                       item.label = dataRow0[index];
                     }
                   });
                 } */
                //需要更新的值
                let updateValues = {
                    cpasData: { ...cpasData, header: new_header },
                    oneHeaders: this.state.oneHeaders,
                    // itemName: this.gridRef.props.itemName || this.gridRef.props.name, // 和左边树节点的交互
                    itemName: itemStrName && itemStrName.split(",")[0],
                    isRowPop: true,
                    titles: "行动态取数",
                    isRow: true,
                    isCol: false,
                    isCell: false,
                    existsRowFormula: false,
                    isShowForm: true, // 告诉子组件正在显示界面,子组件componentDidUpdate方法中用到
                };
                // 行动态公式回显问题
                if (coords.row > 0) {
                    let rowDatas = this.gridRef.data;
                    let rowFormula = rowDatas[coords.row];
                    let lastData = JSON.parse(rowFormula[rowFormula.length - 1]);
                    let formula = lastData.formula;
                    console.log("888--rowDatas--rowFormula", formula, this.state);
                    if (formula) {
                        this.forceUpdate();
                        //去执行回显的方法，到行动态弹窗中回显出关系
                        let colFormula = this.gridRef.getFormulaByCoords(this.gridRef.state.currentRecord.coords, "row");
                        // 编辑行动态弹窗中的公式
                        let copyFormula = colFormula.formula;
                        let reviewFormula = LogicFormulaService.parseLogicFormula("Dr", copyFormula);
                        console.log("888--handSonTool-行动态关系回显", reviewFormula);
                        updateValues = {
                            ...updateValues,
                            // rowSrc2: reviewFormula.first0.dataList,
                            rowSrc2: this.state.rowSrc2,
                            yearSel: reviewFormula.first0.dataId,
                            tab: reviewFormula.first0.activeTab,
                            existsRowFormula: true,
                        };
                        // 两表关系存储回显
                        this.rowTableTraslation = reviewFormula.rowDevCpasMap;
                        this.setState(updateValues);
                    }
                    else {
                        console.log("888--行动态回显无公式");
                        this.rowTableTraslation = [];
                        updateValues = {
                            ...updateValues,
                            saveArr: [],
                            rowSrc2: {},
                            yearSel: "",
                            tab: "11",
                            existsRowFormula: false,
                        };
                        //一次性更新
                        this.setState(updateValues);
                        console.log(this.rowRef, "this.rowRef----");
                        if (this.rowRef?.current) {
                            this.rowRef.current.filterObjArrs = [];
                        }
                    }
                }
            }
            if (e.itemData.name === "列动态取数") {
                // 去拿到cpastable数据
                const cpasDatas = this.gridRef.getCpasTableGrid();
                console.log("888--列动态取数弹窗打开");
                //需要更新的值
                let updateValsCol = {
                    cpasData: cpasDatas,
                    oneHeaders: this.state.oneHeaders,
                    colIndex: coords.col,
                    // itemName: this.gridRef.props.itemName || this.gridRef.props.name, // 和左边树节点的交互
                    itemName: itemStrName && itemStrName.split(",")[0],
                    isRowPop: true,
                    titles: "列动态取数",
                    isCell: false,
                    isRow: false,
                    isCol: true,
                    existsColFormula: false,
                    isShowColForm: true, // 告诉子组件正在显示界面,子组件componentDidUpdate方法中用到
                };
                //列动态,判断点击的列上是否有公式，如果有公式就回显，如果没有公式就不回显
                // if (coords.row === -1) {
                let headers = this.gridRef.headerData;
                let formula = headers[coords && coords?.col].config.formula;
                if (formula) {
                    this.forceUpdate();
                    //去执行回显的方法，到列动态弹窗中回显出关系
                    let colFormula = this.gridRef.getFormulaByCoords(this.gridRef.state.currentRecord.coords, "column");
                    // 列动态弹窗中的公式编辑
                    let copyFormula = colFormula.formula;
                    let reviewFormula = LogicFormulaService.parseLogicFormula("Dc", copyFormula);
                    updateValsCol = {
                        ...updateValsCol,
                        selSrc1: reviewFormula.first0.dataList,
                        yearSel: reviewFormula.first0.dataId,
                        tab: reviewFormula.first0.activeTab,
                        existsColFormula: true,
                    };
                    // 两表关系存储回显
                    this.twoTableTraslation = reviewFormula.cDevCpasMap;
                    // this.setState({
                    //   rowSrc2: this.state.rowSrc2,
                    //   yearSel: reviewFormula.first0.dataId,
                    //   tab: reviewFormula.first0.activeTab,
                    // });
                }
                else {
                    console.log("888--无公式，不回显", this.state.isRowPop, updateValsCol);
                    this.twoTableTraslation = [];
                    updateValsCol = {
                        ...updateValsCol,
                        saveArr: [],
                        rowSrc2: {},
                        yearSel: "",
                        tab: "",
                        existsColFormula: false,
                    };
                    // this.twoTableTraslation = [];
                    // this.setState({
                    //   saveArr: [],
                    //   rowSrc2: {},
                    //   yearSel: "",
                    //   tab: "",
                    // });
                }
                //一次性更新
                this.setState(updateValsCol);
                // }
            }
            if (e.itemData.name === "单元格取数") {
                // 去拿到devtable数据
                const cpasData = this.gridRef.getCpasTableGrid();
                this.setState({
                    cpasData: cpasData,
                    oneHeaders: this.state.oneHeaders,
                });
                this.setState({
                    isRowPop: true,
                    titles: "单元格取数",
                    isCol: false,
                    isRow: false,
                    isCell: true,
                });
                console.log("888--单元格取数", this.state);
            }
        }
        else {
            if (e.itemData.name === "单元格取数") {
                // 去拿到devtable数据
                const cpasData = this.gridRef.getCpasTableGrid();
                this.setState({
                    cpasData: cpasData,
                    oneHeaders: this.state.oneHeaders,
                });
                this.setState({
                    isRowPop: true,
                    titles: "单元格取数",
                    isCol: false,
                    isRow: false,
                    isCell: true,
                });
            }
        }
    };
    init() {
        this.tableEditorService = new TableEditorService(this);
        this.columnEditorService = new ColumnEditorService(this);
        this.rowEditorService = new RowEditorService(this);
        this.handsonTableHeaderService = new HandsonTableHeaderService(this);
        this.collationModeService = new CollationModeService(this);
    }
    resizeUpdate = (e) => {
        this.setState({
            bodyClientWidth: this.tableDesignToolRef.current &&
                this.tableDesignToolRef.current.offsetWidth
                ? this.tableDesignToolRef.current.offsetWidth
                : 0,
        });
    };
    componentDidMount() {
        this.init();
        // this.getComData(); // 企业基础数据-取数源
        // this.getDiGaoOption(); // 底稿名称
        if (this.tableDesignToolRef && this.tableDesignToolRef.current) {
            window.addEventListener("resize", this.resizeUpdate);
        }
        this.setState({
            bodyClientWidth: this.tableDesignToolRef.current
                ? this.tableDesignToolRef.current.offsetWidth
                : 0,
            tabs: [
                {
                    id: 0,
                    text: "表设计",
                },
                {
                    id: 1,
                    text: "取数、校验",
                },
            ],
        });
        this.refreshMenuToolState();
    }
    refreshMenuToolState() {
        const formulaOff = this.gridRef.tableConfig.formulaOff || false;
        const formulaMark = this.gridRef.tableConfig.formulaMark || false;
        const fixedColumnsStart = this.gridRef.tableConfig["fixedColumnsStart"] || false;
        const showRowTag = this.gridRef.tableConfig.showRowTag || false;
        if (fixedColumnsStart && fixedColumnsStart > 0) {
            this.hot.updateSettings({ fixedColumnsStart: fixedColumnsStart + 1 });
        }
        this.setState({
            formulaOff,
            formulaMark,
            fixedColumnsStart,
            showRowTag,
        });
    }
    componentWillUnmount() {
        window.removeEventListener("resize", this.resizeUpdate);
    }
    componentWillReceiveProps(nextProps) {
        // console.log("888--nextprops", nextProps);
        let headers = nextProps.gridRef.headerData;
        if (nextProps.gridRef.state.currentRecord) {
            let coords = nextProps.gridRef.state.currentRecord;
            if (headers && coords.coords.col > 0) {
                if (!headers[coords.coords.col]) {
                    return;
                }
                let getConfig = headers[coords.coords.col].config;
                // console.log("888---formula,nextprops", getConfig, coords.coords.col);
                if (getConfig.formula) {
                    this.forceUpdate();
                    //去执行回显的方法，到列动态弹窗中回显出关系
                    let colFormula = this.gridRef.getFormulaByCoords(coords.coords, "column");
                    // 列动态弹窗中的公式编辑
                    let copyFormula = colFormula.formula;
                    let reviewFormula = LogicFormulaService.parseLogicFormula("Dc", copyFormula);
                    // 两表关系存储回显
                    this.twoTableTraslation = reviewFormula.cDevCpasMap;
                }
                else {
                    // console.log("888--无公式，不回显--nextprops");
                    this.twoTableTraslation = [];
                    this.setState({
                        saveArr: [],
                    });
                    this.forceUpdate();
                }
            }
        }
    }
    // exportToJson() {} // 导出json 已抽到 HandsonTableHeaderService
    /**
     * 导出为Excel
     */
    exportToExcel() {
        this.ExportToExcel(this.props.name);
    }
    excelImport(file) {
        this.ImportExcel(file);
        this.gridRef.dataFrom = "import";
        resetSessionDismantleData();
    }
    /**
     * 导出到底稿平台
     */
    exportToDraft() {
        const ref = this.draftPopupRef;
        const { draftSheetName } = this.props;
        this.ExportToDraft({
            draftPopupRef: this.draftPopupRef,
            //draftFilePath,
            draftSheetName,
        });
    }
    /**
     * save 保存到数据库
     */
    async save() {
        const reuslt = await this.gridRef.saveToServer();
        if (reuslt) {
            this.showSuccessNotify("表格保存成功");
        }
        else {
            this.showErrorNotify("表格保存失败");
        }
    }
    /**
     * 获取列配置信息,并且更新状态
     * @param coords
     */
    updateColumnState(coords, userClickedHeaderMeta) {
        const { row, col } = coords;
        if (col < 0) {
            return;
        }
        const columnInfo = userClickedHeaderMeta;
        this.setState({
            keywordState: columnInfo.config.keyword,
            pExclude: columnInfo.config["p_exclude"],
            cExclude: columnInfo.config["c_exclude"],
        });
        this.setState({
            currentColumnName: columnInfo.label,
        });
        if (columnInfo.type === "header") {
            const numericFormat = columnInfo?.config?.numericFormat?.pattern;
            if (numericFormat && numericFormat.includes("%")) {
                this.setState({
                    currentColumnType: "percent",
                });
            }
            else {
                this.setState({
                    currentColumnType: columnInfo.config.type,
                });
            }
        }
        else {
            this.setState({
                currentColumnType: "",
            });
        }
        this.setState({
            currentQiJianType: columnInfo.config.qiJianType
                ? columnInfo.config.qiJianType
                : "none",
        });
        this.setState({
            isReverse: columnInfo.config.isReverse,
        });
        if (columnInfo.config?.c_polymeric) {
            this.setState({
                cellPType: columnInfo.config?.c_polymeric.type,
            });
        }
        else {
            this.setState({
                cellPType: "",
            });
        }
    }
    /**
     * 以前更新列状态的方式，有性能问题暂时保留
     * @param coords
     */
    // updateColumnState_bak(key, coords) {
    //   const { row, col } = coords;
    //   if (col < 0) {
    //     return;
    //   }
    //   //设置列信息
    //   let columnInfo;
    //   //可点击列
    //   if (row < -1) {
    //     columnInfo = this.headerService.findNodeByKey(
    //       key,
    //       this.headerService.headJson
    //     );
    //   } else {
    //     columnInfo = this.headerService.getHeaderConfigByIndex(
    //       this.headerService.headJson,
    //       col
    //     );
    //   }
    //
    //   this.setState({
    //     keywordState: columnInfo.config.keyword,
    //   });
    //
    //   this.setState({
    //     currentColumnName: columnInfo.label,
    //   });
    //
    //   if (row > -2) {
    //     this.setState({
    //       currentColumnType: columnInfo.config.type,
    //     });
    //   } else {
    //     this.setState({
    //       currentColumnType: "",
    //     });
    //   }
    //
    //   this.setState({
    //     currentQiJianType: columnInfo.config.qiJianType
    //       ? columnInfo.config.qiJianType
    //       : "none",
    //   });
    //
    //   this.setState({
    //     isReverse: columnInfo.config.isReverse,
    //   });
    // }
    /**
     * setToolBarState , 由 GridHook 触发;
     */
    setToolBarState(coords) {
        if (coords.row < 0) {
            return;
        }
        const cellMeta = this.hot.getCellMeta(coords.row, coords.col > -1 ? coords.col : 0);
        //获取公式值
        const sourceData = this.hot.getSourceDataAtCell(coords.row, coords.col > -1 ? coords.col : 0);
        const { r_polymeric = {}, c_polymeric = {}, operator_r = {} } = cellMeta;
        let rowPType = "";
        let cellPType = "";
        console.log(cellMeta, "cellMeta--------");
        const tags = r_polymeric?.tagType ? r_polymeric?.tagType : "";
        const c_tags = c_polymeric?.tagType ? c_polymeric?.tagType : "";
        const operatorTag = operator_r?.operatorTag ? operator_r?.operatorTag : "";
        //行聚合回显数据
        if (r_polymeric?.type && tags) {
            rowPType = r_polymeric?.type || "";
        }
        //列聚合回显数据
        if (c_polymeric?.type && c_tags) {
            cellPType = c_polymeric?.type || "";
        }
        console.log(rowPType, "rowPType----cellPType", cellPType);
        if (cellMeta["custom"]) {
            // 判断一下缩进类型，兼容以前写法
            let rConfig = cellMeta["custom"]["r"];
            // 以前r 是一个数值 , 现在是个对象
            if (rConfig) {
                if (typeof rConfig === "number") {
                    rConfig = {
                        type: 1,
                        val: rConfig,
                    };
                }
            }
            let cell_ht = cellMeta["custom"]["ht"];
            if (!cell_ht) {
                cell_ht = cellMeta.type === "text" ? 1 : 3;
            }
            this.setState({
                ...this.state,
                rowPType,
                cellPType,
                isRowOperatorTag: operatorTag ? true : false,
                bl: cellMeta["custom"]["bl"] || defaultCellStyle.bl,
                it: cellMeta["custom"]["it"] || defaultCellStyle.it,
                fc: cellMeta["custom"]["fc"] || defaultCellStyle.fc,
                bg: cellMeta["custom"]["bg"] || defaultCellStyle.bg,
                r: rConfig || defaultCellStyle.r,
                ht: cell_ht,
                percentFormat: cellMeta["isPercentFormat"],
                currentColumnMap: cellMeta["custom"]["cmap"] || cellMeta["cmap"] || "",
                currentRowMap: cellMeta["custom"]["rmap"] || cellMeta["rmap"] || "",
                weightType: cellMeta["custom"]["w"] || cellMeta["w"] || "",
            });
        }
        else {
            this.setState({
                ...this.state,
                bl: defaultCellStyle.bl,
                r: defaultCellStyle.r,
                it: defaultCellStyle.it,
                bg: defaultCellStyle.bg,
                fc: defaultCellStyle.fc,
                ht: cellMeta.type === "text" ? 1 : 3,
                percentFormat: cellMeta["isPercentFormat"],
                rowPType,
                cellPType,
                isRowOperatorTag: operatorTag ? true : false,
                currentColumnMap: cellMeta["cmap"] || "",
                currentRowMap: cellMeta["rmap"] || "",
                weightType: cellMeta["w"] || "",
                currentOperationalFormula: sourceData ?? "",
                currentVerifyFormula: cellMeta["v"] || "",
            });
        }
    }
    setQiJianType(currentQiJianType) {
        this.setState({
            currentQiJianType,
        });
    }
    setHeaderState(headerHt) {
        this.setState({
            headerHt,
        });
    }
    setHeaderBlState(headerBl) {
        this.setState({
            headerBl,
        });
    }
    setHeaderPercentFormatState(headerPf) {
        this.setState({
            percentFormat: headerPf,
        });
    }
    throttleColumnNameChange = _.throttle((e) => {
        this.columnNameChange(e);
    }, 500);
    // 列聚合改变回调
    showWenZiPanel() {
        this.setState({
            wenziPanelVisible: true,
        });
    }
    hideWenZiPanel() {
        this.setState({
            wenziPanelVisible: false,
        });
    }
    hideSetTagPanel() {
        this.setState({
            isOpenSetTag: false,
        });
    }
    hideLabelJuHePanel() {
        this.setState({
            isOpenPolymeric: false,
        });
    }
    hideLabelCustomOperation() {
        this.setState({
            isOpenCustomOperation: false,
        });
    }
    columnTypeChange(e) {
        const option_value = e.itemData.id;
        if (!this.gridRef.state.currentRecord) {
            this.showErrorNotify("请选择表头进行操作");
            return;
        }
        //type 类型只能按照handson提供的内置数据类型。 例如百分比，千分位符，这些属于 numeric 类型的格式化显示需要单独处理
        let params;
        if (option_value === "percent") {
            params = {
                numericFormat: {
                    pattern: "0.00%",
                },
                type: "numeric",
            };
        }
        else if (option_value === "numeric") {
            params = {
                numericFormat: {
                    pattern: "0,00.00",
                },
                type: "numeric",
            };
        }
        else {
            params = {
                numericFormat: {
                    pattern: "",
                },
                type: "text",
            };
        }
        const col = this.gridRef.state.currentRecord.coords.col;
        const update_header = this.headerService.updateHeaderConfigByIndex(this.headerService.headJson, col, params);
        this.headerService.headerCompute(update_header);
        this.setState({
            currentColumnType: option_value,
        });
        // 重新计算主键
        // this.reComputerPrimeryKey(); //@20241209注释掉该代码，该代码会产生问题修改数据类型后重新计算rmap，导致用户修改rmap后，计算主键不正确
        this.gridRef.hot.render();
        this.gridRef.hot.validateCells();
        this.formulaService.refreshAllPolymeric();
        this.gridRef.setTableContentChange(true, {
            type: "更改数据类型",
            params: { dataType: option_value },
        });
    }
    /**
     * 列名称
     */
    columnNameChange = (e) => {
        const coords = this.gridRef.state.currentRecord.coords;
        const isParentHeader = this.headerService.isParentHeader(coords);
        const { row, col } = coords;
        if (row > -1) {
            this.showErrorNotify("请选择表头进行设置");
            return;
        }
        const val = e.target.value;
        //如果是披露表类型，自动设置cmap值
        // if (this.gridRef.props.type === "ds" || this.gridRef.props.type === "zl") {
        //   if (!isParentHeader) {
        //     const cmap = this.hot.getDataAtCell(0, col);
        //     //和rmap修改逻辑保持一致，只不过列的cmap在增列的时候不会为空并且一定和列名相等,所以不需要判断
        //     if (cmap === this.headerService.headerColumn[col].label) {
        //       this.hot.setDataAtCell(0, col, val);
        //     }
        //   }
        // }
        const update_header = this.headerService.updateNodeByKey(this.gridRef.state.currentRecord.key, this.headerService.headJson, {
            label: val,
        });
        const oldHeaderColumn = this.headerService.headerColumn;
        this.headerService.headerCompute(update_header);
        this.gridService.autoFillCmap(oldHeaderColumn);
        // e.target.focus();
        this.gridRef.setTableContentChange(true, {
            type: "更改列名称",
            params: { label: val },
        });
    };
    /**
     * 删除行
     */
    removeRowHandle() {
        const range = this.gridRef.state.currentRange;
        if (!range) {
            this.showErrorNotify("请选择行进行操作");
            return;
        }
        this.gridService.removeRows(this.gridRef.state.currentRange);
        this.gridRef.setTableContentChange(true, {
            type: "删行",
            params: { range: this.gridRef.state.currentRange },
        });
    }
    /****
     * 删除列
     */
    removeColumnHandle(needDeleteKey) {
        if (needDeleteKey) {
            this.gridService.removeColumn(needDeleteKey);
            return;
        }
        if (!this.gridRef.state.currentRecord) {
            this.showErrorNotify("请选择表头进行操作");
            return;
        }
        if (!this.gridRef.state.currentRecord.key) {
            this.showErrorNotify("请选择表头进行操作");
            return;
        }
        const key = this.gridRef.state.currentRecord.key;
        this.gridService.removeColumn(key);
        this.gridRef.setTableContentChange(true, {
            type: "删列",
            params: { key },
        });
    }
    /**
     * 新增列
     */
    insertColumnHandle(e, isCopy) {
        if (this.headerService.headerColumn.length > 102) {
            this.showErrorNotify("最多只能新增100列");
            return;
        }
        const { id } = e.itemData;
        let type = "";
        if (id === 1) {
            type = "right";
        }
        else if (id === 2) {
            type = "left";
        }
        else {
            type = "child";
        }
        //TODO 暂时没处理不选择表头增加列的处理逻辑,需求未要求.因为涉及到列标签的功能
        if (!this.gridRef.state.currentRecord) {
            this.showErrorNotify("请选择表头进行操作");
            return;
        }
        if (!this.gridRef.state.currentRecord.key) {
            this.showErrorNotify("请选择表头进行操作");
            return;
        }
        const key = this.gridRef.state.currentRecord.key;
        const col = this.gridRef.state.currentRecord.coords.col;
        if (col === 0 && type === "right") {
            // 处理在主键右侧插列 单元格背景不能设置问题 bug-452
            isCopy = false;
        }
        this.gridService.addColumn(type, isCopy, key);
        this.gridRef.setTableContentChange(true, {
            type: "插列",
            params: { type, isCopy, key },
        });
    }
    /**
     * 导入
     */
    configFileUpload = (file) => {
        localStorage.userAction = "clickedImport";
        const reader = new FileReader();
        reader.onload = (event) => {
            const str_result = event.target.result;
            const json_result = JSON.parse(str_result);
            // 现在不需要刷id，后台已和tid创建联合主键
            // const newData = this.gridService.resetCpasTableId(json_result);
            if (this.gridRef.props.beforeJsonImport) {
                this.gridRef.props.beforeJsonImport(json_result);
            }
            this.gridRef.dataFrom = "import";
            this.gridRef.reloadTable(json_result);
        };
        reader.readAsText(file);
    };
    importHandle(e) {
        const { id } = e.itemData;
        if (id === 1) {
            //json
            //读取的json字符串
            // this.gridRef.reloadTableData(JSON.parse(str_result));
        }
        else {
            //excel
        }
    }
    /**
     * 设置表格冻结列
     */
    setFixedColumnsStart(value) {
        this.setState({
            ...this.state,
            fixedColumnsStart: value,
        });
        if (value === null) {
            this.hot.updateSettings({ fixedColumnsStart: 0 });
        }
        else {
            this.hot.updateSettings({ fixedColumnsStart: value + 1 });
        }
        // handsontable 需要在原值上+1
        this.gridRef.tableConfig["fixedColumnsStart"] = value;
        this.gridRef.setTableContentChange(true, {
            type: "设置表格冻结",
            params: { fixedColumnsStart: value },
        });
    }
    /**
     * 设置缩进
     */
    setCellRetract(value) {
        if (!this.gridRef.state.currentRange) {
            this.showErrorNotify("请选择单元格进行操作");
            return;
        }
        const val = {
            type: this.state.r.type,
            val: value,
        };
        const currentRange = this.gridRef.state.currentRange;
        // this.gridService.setRetractToCell(value, currentRange);
        this.gridService.setCellConfig({
            r: val,
        }, currentRange);
        this.setState({
            r: val,
        });
        this.gridRef.setTableContentChange(true, {
            type: "设置单元格缩进",
            params: { r: val },
        });
    }
    /**
     * 设置小数位
     */
    setDp(type) {
        if (!this.gridRef.state.currentRange) {
            this.showErrorNotify("请选择单元格进行操作");
            return;
        }
        this.gridService.setCellDecimalConfig(type, this.gridRef.state.currentRange);
        this.gridRef.setTableContentChange(true, {
            type: "设置小数位",
            params: { type },
        });
    }
    /**
     * 设置行映射
     * @param value
     */
    onChangeRowMap(e) {
        const value = e.value;
        if (!e.event || !this.gridRef.state.currentRange) {
            return;
        }
        //todo 不支持挑选划范围，目前仅支持第一段
        const range = this.gridRef.state.currentRange[0];
        const from_row = range.from.row;
        const to_row = range.to.row + 1;
        for (let i = from_row; i < to_row; i++) {
            this.gridService.setRowConfig(i, { rmap: value });
        }
        this.setState({
            ...this.state,
            currentRowMap: value,
        });
    }
    /**
     * 设置列映射
     * @param value
     */
    onChangeColumnMap(e) {
        const value = e.value;
        if (!e.event || !this.gridRef.state.currentRange) {
            return;
        }
        //todo 不支持挑选划范围，目前仅支持第一段
        const range = this.gridRef.state.currentRange;
        this.headerService.bathUpdateHeaderConfigByIndex(range, {
            cmap: value,
        });
        this.setState({
            ...this.state,
            currentColumnMap: value,
        });
    }
    getTag() {
        const currentRange = this.gridRef.state.currentRange;
        this.tagService.getTag(currentRange);
    }
    /**
     * 设置列为百分号显示列
     */
    setPercentFormat() {
        if (!this.gridRef.state.currentRecord) {
            return;
        }
        const { row, col } = this.gridRef.state.currentRecord.coords;
        if (!col && col < 0) {
            return;
        }
        const isPercentFormat = !this.state.percentFormat;
        const update_header = this.headerService.updateHeaderConfigByIndex(this.headerService.headJson, col, {
            isPercentFormat: isPercentFormat,
        });
        this.setState({
            percentFormat: isPercentFormat,
        });
        this.headerService.headerCompute(update_header);
        // this.hot.validateCells();
        this.gridRef.setTableContentChange(true, {
            type: "设置百分号展示",
            params: { col },
        });
    }
    /**
     * 设置列为关键字段
     */
    setColumnKeyword() {
        if (!this.gridRef.state.currentRecord) {
            return;
        }
        const { row, col } = this.gridRef.state.currentRecord.coords;
        if (!col && col < 0) {
            return;
        }
        const currentKeywordState = !this.state.keywordState;
        const update_header = this.headerService.updateHeaderConfigByIndex(this.headerService.headJson, col, {
            keyword: currentKeywordState,
            strict: !currentKeywordState,
        });
        this.setState({
            keywordState: currentKeywordState,
        });
        this.headerService.headerCompute(update_header);
        // this.hot.validateCells();
        // 重新计算主键
        this.reComputerPrimeryKey();
        this.gridRef.setTableContentChange(true, {
            type: "设置合并项目列",
            params: { col },
        });
    }
    reComputerPrimeryKey() {
        const keywordsColumnIndex = 0;
        const tableRowCount = this.hot.countRows();
        const tableColCount = this.hot.countCols();
        console.log("tableColCount", tableColCount);
        const mapsChanged = [];
        for (let row = 0; row < tableRowCount; row++) {
            // 遍历每行
            // 拼接列，然后赋值给主键
            let primaryContentAfter = "";
            for (let i = 0; i < tableColCount - 1; i++) {
                if (i != keywordsColumnIndex) {
                    const perCellContent = this.hot.getDataAtCell(row, i);
                    const cellMeta = this.hot.getCellMeta(row, i);
                    if (perCellContent != null &&
                        perCellContent != "" &&
                        cellMeta.type === "text" &&
                        cellMeta.keyword) {
                        // 必须是合并项目列且列类型为文本才拼接
                        primaryContentAfter = primaryContentAfter + perCellContent + "-";
                    }
                }
            }
            const deleteLastHorizontalLinePrimaryContent = primaryContentAfter.substring(0, primaryContentAfter.length - 1);
            mapsChanged.push([
                row,
                keywordsColumnIndex,
                deleteLastHorizontalLinePrimaryContent,
            ]);
        }
        if (mapsChanged.length > 0) {
            this.hot.setDataAtRowProp(mapsChanged);
        }
    }
    /**
     * 行列打标签
     * @param type
     * @param tagName
     */
    async setTag(type, tagName, tagType = "", row = null, col = null) {
        let currentRange = this.gridRef.state.currentRange;
        const coords = this.gridRef.state.currentRecord.coords;
        const rowIndex = coords && coords.row ? coords.row : 1;
        const colIndex = coords && coords.col ? coords.col : 1;
        //let isRowColumnTag = false;
        //const isTop = tagName.includes("TOP--"); //是否是行聚合标签
        //const isLeft = tagName.includes("LEFT--"); //是否是列聚合标签
        //行聚合重新计算可选范围
        //if (isTop) {
        if (tagType === "top") {
            if (+rowIndex < 2) {
                return message.error("操作行聚合运算的单元格位置不对");
            }
            for (let i = 0; i < currentRange.length; i++) {
                const item = currentRange[i];
                if (item.highlight || item.from) {
                    item.highlight.row = 1;
                }
                if (item.from) {
                    item.from.row = 1;
                }
                if (item.to) {
                    item.to.row = rowIndex - 1;
                }
            }
            //isRowColumnTag = true;
        }
        //列聚合重新计算可选范围
        if (tagType === "left") {
            //const colIndex = newCurrentRange ? newCurrentRange[0].to.col : 1;
            if (+colIndex < 2) {
                return message.error("操作列聚合运算的单元格位置不对");
            }
            for (let i = 0; i < currentRange.length; i++) {
                const item = currentRange[i];
                if (item.highlight || item.from) {
                    item.highlight.col = 1;
                }
                if (item.from) {
                    item.from.col = 1;
                }
                if (item.to) {
                    item["to"]["col"] = colIndex - 1;
                }
            }
            //isRowColumnTag = true;
        }
        let { rows, cols } = this.gridService.getRangeRowsAndColumn(currentRange);
        if (row) {
            rows = row;
        }
        if (col) {
            cols = col;
        }
        if (type === "row") {
            //设置行配置
            this.tagService.setRowTags(tagName, rows);
            //重新赋值一下所有标签
            if (tagType !== "top") {
                this.setState({
                    allRowTags: [...this.tagService.getAllTag("row")],
                });
            }
        }
        else {
            //设置列配置
            this.tagService.setColumnTags(tagName, cols, (update_config_headerJson) => {
                this.headerService.headerCompute(update_config_headerJson);
            });
            //更新列的所有标签
            if (tagType !== "left") {
                this.setState({
                    allColumnTags: [...this.tagService.getAllTag("column")],
                });
            }
        }
        //刷新公式@todo迁移后台
        await this.formulaService.refreshAllPolymeric();
        //this.formulaService.refreshAllPolymericColumn();
        //this.formulaService.refreshAllPolymericRow();
        /*this.setState({
          isRowColumnTag,
        });*/
        this.gridRef.setTableContentChange(true, {
            type: "设置行列标签",
            params: { type, tagName, tagType, row, col },
        });
        // 对于公式起别名策略 ,  暂时验证更改公式方案。不用起别名方式
        // const tags = conditionMatchTagValue(tagName);
        // hyper.current.addNamedExpression(tagName, tags.join(","));
    }
    //设置聚合行计算方式
    async setRowCountType(type, tags, tagType) {
        const { row, col } = this.gridRef.state.currentRecord.coords;
        if (row < 1) {
            return false;
        }
        //设置行聚合配置
        const cpasTableData = await this.formulaService.setRowPolymericToRowConfig(row, {
            type: type,
            tags: tags,
            tagType,
        });
        await this.formulaService.getRefreshPolymericRowFormula([row], cpasTableData);
        this.tagService.refreshTagColumn(this, [row]);
        //this.formulaService.refreshPolymericRowFormula([row]);
        this.gridRef.setTableContentChange(true, {
            type: "设置行聚合运算",
            params: { type, tags, tagType },
        });
    }
    //设置列聚合方式
    async setColumnCountType(type, tags, tagType) {
        const { row, col } = this.gridRef.state.currentRecord.coords;
        if (col < 2) {
            return false;
        }
        const cpasTableData = await this.formulaService.setColumnPolymericToColumnConfig(col, {
            c_polymeric: {
                type: type,
                tags: tags,
                tagType,
            },
            tagType,
        });
        await this.formulaService.getRefreshPolymericColumnFormula([col], cpasTableData);
        //this.formulaService.refreshPolymericColumnFormula([col]);
        this.gridRef.setTableContentChange(true, {
            type: "设置列聚合运算",
            params: { type, tags, tagType },
        });
    }
    //设置行运算符
    async setRowOperatorType(type) {
        const { row, col } = this.gridRef.state.currentRecord.coords;
        let typeName = "设置行运算标签";
        if (type === "del") {
            typeName = "删除行运算标签";
            this.tagService.handleDeleteRowOperatorLabel();
        }
        else {
            //设置行聚合配置
            await this.formulaService.setRowOperatorToRowConfig(row, {
                operatorTag: "row",
            }, type);
        }
        this.gridRef.setTableContentChange(true, {
            type: typeName,
            params: { operatorTag: "row" },
        });
    }
    polymerizationTypeChange = (value) => {
        this.setState({
            pType: value,
        });
    };
    selectTagsChange = (value) => {
        const tagType = this.state.tagType;
        console.log(tagType, "tagType111");
        if (tagType === "row") {
            this.tagService.handleDeleteJuHeRowLabel(value); // 删除聚合行标签
        }
        else {
            this.tagService.handleDeleteJuHeColLabel(value); // 删除聚合列标签
        }
        this.setState({
            currentSelectedTags: [...value],
        });
    };
    selectRowColumnTagsChange = (tagType) => {
        console.log(tagType, "tagType11111");
        if (tagType === "row") {
            this.tagService.handleDeleteJuHeRowLabel([], true); // 删除聚合行标签
        }
        else {
            this.tagService.handleDeleteJuHeColLabel([], true); // 删除聚合列标签
        }
    };
    openCustomOperation() {
        if (!this.gridRef.state.currentRecord) {
            return;
        }
        const { row } = this.gridRef.state.currentRecord.coords;
        if (row < 0) {
            return;
        }
        const weightInfo = this.formulaService.getCustomWeightInfoByRow(row);
        // const cw = weightInfo?.cw; //自定义权重
        if (weightInfo) {
            let lists = [];
            //需要适配后端，做数据转换
            for (let key in weightInfo) {
                if (key) {
                    const arr = Object.keys(weightInfo[key]);
                    lists.push({
                        rmap: key,
                        type: arr[0],
                    });
                }
            }
            if (lists && lists.length) {
                this.setState({
                    currentOperationLists: lists,
                });
            }
        }
        else {
            this.setState({
                currentOperationLists: [],
            });
        }
        this.setState({
            isOpenCustomOperation: true,
        });
    }
    addCustomOperation() {
        let currentOperationLists = this.state.currentOperationLists;
        this.setState({
            currentOperationLists: [
                ...currentOperationLists,
                {
                // rmap: '',
                // type: ''
                },
            ],
        });
    }
    openPolyMeric(type) {
        this.setState({
            tagType: type,
        });
        if (!this.gridRef.state.currentRecord) {
            return;
        }
        const { row, col } = this.gridRef.state.currentRecord.coords;
        let polyMericInfo;
        if (type === "row") {
            polyMericInfo = this.formulaService.getPolymerizationInfoByRow(row);
        }
        else {
            polyMericInfo = this.formulaService.getColumnPolymericToColumnConfig(col);
        }
        const tagType = polyMericInfo && polyMericInfo.tagType ? polyMericInfo.tagType : ""; //默认为空，只有在设置了行聚合和列聚合的情况下才有数据
        console.log(polyMericInfo, "polyMericInfo render");
        //排除掉行聚合和列聚合
        if (polyMericInfo && !tagType) {
            console.log("进入条件");
            this.setState({
                currentSelectedTags: [...polyMericInfo.tags],
                pType: polyMericInfo.type,
            });
        }
        else {
            this.setState({
                currentSelectedTags: [],
                pType: "SUM",
            });
        }
        this.setState({
            isOpenPolymeric: true,
        });
    }
    // openSetTag(type) {} // 已抽取到 RowEditorService
    /**
     * 设置权重
     * @param type
     * @param weightType
     */
    setWeight(type, weightType) {
        this.tagService.setWeight(type, weightType, this.gridRef.state.currentRange);
        this.gridRef.setTableContentChange(true, {
            type: "标签权重(中/减)设置",
            params: { type, weightType },
        });
    }
    /**
     * 设置行标签列展示
     */
    setShowRowTags() {
        const oldTableContentIsChange = this.gridRef.tableContentIsChange;
        const isShowRowTag = !this.state.showRowTag;
        this.gridRef.tableConfig["showRowTag"] = isShowRowTag;
        if (isShowRowTag) {
            this.setState({
                maskValue: "block",
            });
        }
        else {
            this.setState({
                maskValue: "none",
            });
        }
        // 设置状态
        this.setState({
            showRowTag: isShowRowTag,
        });
        this.tagService.isShowTagColumn(isShowRowTag, this.gridRef);
        const tableContentIsChange = oldTableContentIsChange ? true : false;
        this.gridRef.tableContentIsChange = tableContentIsChange;
        this.gridRef.setTableContentChange(tableContentIsChange, {
            type: "设置行标签列展示",
            params: { showRowTag: isShowRowTag },
        });
    }
    /**
     * 聚合豁免|聚合不参与
     * excludeType： p是豁免， c是不参与
     */
    setPolymericExclude(type, excludeType) {
        this.tagService.setPolymericExclude(type, excludeType);
        this.gridRef.setTableContentChange(true, {
            type: excludeType === "p" ? "行列豁免设置" : "行聚合不参与设置",
            params: { type },
        });
    }
    /**
     * 打开设置分组弹窗
     */
    openSetGroupByKeyword() {
        console.log("获取keyword----------------");
        const matchColumn = this.gridService.getColumnIndexByConfig("keyword", true);
        this.setState({
            keyword: [...matchColumn],
            isOpenSetGroup: true,
        });
    }
    /**
     * 执行分组逻辑
     */
    generateGroup() {
        const currentGroupKeyColumn = this.state.currentGroupKeyColumn;
        this.currentGroupInfo = this.gridService.generateGroup(currentGroupKeyColumn);
        this.gridRef.tableConfig = {
            isGroup: true,
            currentGroupKeyColumn: this.state.currentGroupKeyColumn,
        };
    }
    /**
     * 设置分组选择的关键字段
     */
    currentGroupKeyColumnChange = (value) => {
        this.setState({
            currentGroupKeyColumn: value,
        });
    };
    /**
     * @todo隐藏显示行列关系--后期要移除，如有使请使用HandSonGrid实例上的方法
     */
    setRowColumnsMap() {
        this.gridRef.isShowMaps = !this.gridRef.isShowMaps;
        this.gridService.hiddenColumnAndRow();
    }
    /**
     * sync 自动同步行关系
     */
    /**
     * 运算公式栏
     */
    operationalFormulaChanged(e) {
        const value = e.value;
        this.setState({
            currentOperationalFormula: value,
        });
    }
    /**
     * 校验公式
     */
    verifyFormulaChanged(e) {
        const value = e.value;
        this.setState({
            currentVerifyFormula: value,
        });
    }
    /**
     * 失去焦点或者回车的情况
     */
    formulaChanged(e, type) {
        const record = this.gridRef.state.currentRecord;
        if (!record) {
            return;
        }
        const { row, col } = record.coords;
        if (type === "o") {
            this.hot.setSourceDataAtCell(row, col, this.state.currentOperationalFormula);
        }
        else {
            const vFormula = this.state.currentVerifyFormula;
            this.hot.setCellMeta(row, col, "v", vFormula);
            const dValue = this.hot.getDataAtCell(row, col);
            this.hot.validateCell(dValue, this.hot.getCellMeta(row, col), (v) => {
                console.log(v);
            }, "test");
        }
    }
    /**
     * 设置公式栏值
     * @param value
     * @param type o运算公式, v验证公式
     */
    setFormulaStateData(value, type) {
        if (type === "o") {
            this.setState({
                currentOperationalFormula: value,
            });
        }
        else {
            this.setState({
                currentVerifyFormula: value,
            });
        }
    }
    syncColumnMaps() {
        this.gridService.autoFillCmap();
    }
    syncRowMas() {
        //如果是联合主键用 xx-xx 拼装。并且外面传入的数据源必须支持 '-' 拼接形式的联合主键；
        const keywords = this.headerService.getKeywordColumnIndex();
        if (keywords.length < 1) {
            this.showErrorNotify("请设置合并项目列");
            return;
        }
        const keywords_column_data = [];
        keywords.forEach((item) => {
            const column_datas = this.hot.getDataAtCol(item);
            keywords_column_data.push(column_datas);
        });
        const item_column = this.hot.getDataAtCol(keywords[0]);
        const auto_fill_values = [];
        item_column.forEach((firstColumnValue, firstColIndex) => {
            if (firstColIndex === 0) {
                return true;
            }
            const value = [];
            keywords_column_data.forEach((columnData) => {
                value.push(columnData[firstColIndex]);
            });
            if (keywords.length > 1) {
                auto_fill_values.push([firstColIndex, 0, value.join("-")]);
            }
            else {
                auto_fill_values.push([firstColIndex, 0, value.join("")]);
            }
        });
        this.hot.setDataAtRowProp(auto_fill_values);
        this.gridRef.setTableContentChange(true, {
            type: "同步匹配关系",
            params: null,
        });
    }
    setMask(value) {
        this.setState({
            maskValue: value,
        });
    }
    tableDesignToolsRender() {
        const { sliderPosition, bodyClientWidth } = this.state;
        console.log(bodyClientWidth, "bodyClientWidth test");
        const toolsCurrent = this.tableToolsRef.current;
        let sliderWidth = 0;
        let scrollWidth = 0;
        if (toolsCurrent) {
            sliderWidth = toolsCurrent.clientWidth;
            scrollWidth = toolsCurrent.scrollWidth;
        }
        const endVal = sliderWidth - scrollWidth - 20;
        const mergeType = getHbTypeByZcbfid();
        const sysName = getCurrentSysName();
        let bodyWidth = sysName !== SystemName.MERGE ? 1600 : 850;
        if (mergeType === MergeType.TEMPLATE) {
            bodyWidth = 1600;
        }
        return (_jsxs("div", { className: "table-design-tools", ref: this.tableDesignToolRef, children: [_jsx("div", { className: "table-design-mask", style: { display: this.state.maskValue } }), _jsx("div", { className: "handson-tab-icon handson-tab-lf", onClick: () => this.handleArrowClick("prev"), style: {
                        display: sliderPosition === 0 || bodyClientWidth > bodyWidth
                            ? "none"
                            : "flex",
                    }, children: _jsx("span", { className: "iconfont icon-chevron-left" }) }), _jsx("div", { className: "table-design-tools-content", ref: this.tableToolsRef, style: { transform: `translateX(${sliderPosition}px)` }, children: _jsx(Editor, { _this: this }) }), _jsx("div", { className: "handson-tab-icon handson-tab-ri", onClick: () => this.handleArrowClick("next"), style: {
                        display: sliderPosition === endVal || bodyClientWidth > bodyWidth
                            ? "none"
                            : "flex",
                    }, children: _jsx("span", { className: "iconfont icon-chevron-right" }) })] }));
    }
    onTabsSelectionChanged(args) {
        if (args.name === "selectedIndex") {
            this.setState({
                selectedIndex: args.value,
            });
            //重置表格高度
            this.gridRef.reRender();
        }
    }
    showErrorNotify(msg) {
        this.menuToolNotifyRef.current.show({
            type: "warning ",
            message: msg,
        });
    }
    showSuccessNotify(msg) {
        this.menuToolNotifyRef.current.show({
            type: "success ",
            message: msg,
        });
    }
    //得到关系 // 接受弹窗中建立的两表关系
    getTraslate = (data) => {
        console.log("888--弹窗列动态两表关系", data);
        this.setState({
            saveArr: data,
        });
    };
    // 年度下拉值
    getYearVal = (data) => {
        console.log("888--传过来的年度data");
        this.setState({
            yearSel: data,
        });
    };
    getYearSel1 = (data) => {
        this.setState({
            yearSel1: data,
        });
    };
    getYearSel2 = (data) => {
        this.setState({
            yearSel2: data,
        });
    };
    // 取数源表名--列动态
    getDsrc1 = (data) => {
        // console.log("888---取数源表名--列动态", data);
        this.setState({
            selSrc1: data,
        });
    };
    getTbname1 = (data) => {
        this.setState({
            tbName1: data,
        });
    };
    getTbname2 = (data) => {
        this.setState({
            tbName2: data,
        });
    };
    getProjectName1 = (data) => {
        this.setState({
            projectName1: data,
        });
    };
    getProjectName2 = (data) => {
        this.setState({
            projectName2: data,
        });
    };
    getDigaoName = (data) => {
        this.setState({
            reportItem: data,
        });
    };
    // 列动态--表格列头
    getcolums = (data) => {
        console.log("888--data--表格列头");
        this.setState({
            columnsData: data,
        });
    };
    //行动态---数据源表名
    getrowSrc2event = (data) => {
        console.log("888--getrowSrc2event", data);
        this.setState({
            rowSrc2: data,
        });
    };
    // 得到行动态弹窗中 底稿结构化 - 附加条件 筛选
    getWhere = (data) => {
        this.setState({
            objChild: data,
        });
    };
    getConditions = (data) => {
        this.setState({
            conditonStr: data,
        });
    };
    getTop = (data) => {
        console.log("888a--top", data);
        this.setState({
            top: data,
        });
    };
    activeTab = (data) => {
        console.log("888--activeTab", data);
        this.setState({
            tab: data,
        });
    };
    activeTab1 = (data) => {
        console.log("888--activeTab1", data);
        this.setState({
            tab1: data,
        });
    };
    activeTab2 = (data) => {
        console.log("888--activeTab2", data);
        this.setState({
            tab2: data,
        });
    };
    // 只用于单元格取数弹窗中获取row col
    getCoords = (data) => {
        console.log("888--单元格取数弹窗中data", data);
        this.setState({
            coords: data,
        });
    };
    // 封装数组去重方法:根据提供的属性去重,勿删，否则影响定义公式中的drMaps 数据格式要求
    // arrDistinctByProp(arr: any, prop: any) {
    //   let obj = {};
    //   return arr.reduce((preValue, item) => {
    //     if (
    //       obj[item[prop]] ? "" : (obj[item[prop]] = true && preValue.push(item))
    //     ) {
    //       return preValue;
    //     } else {
    //       return preValue;
    //     }
    //   }, []);
    // }
    // 封装数组去重方法:根据提供的属性去重,勿删，否则影响定义公式中的drMaps 数据格式要求
    quchong(data) {
        const uniqueData = Object.values(data.reduce((dict, item) => {
            if (!dict[item.sourceMap] ||
                dict[item.sourceMap].dataListMap !== item.dataListMap) {
                dict[item.sourceMap] = item;
            }
            return dict;
        }, {}));
        return uniqueData;
    }
    // 定义公式
    async generateLogicFormula(state) {
        console.log("888--定义公式 HandsonTool", state);
        let sessionParam = JSON.parse(window.sessionStorage.getItem("electronParams"));
        if (state.titles === "行动态取数") {
            /* let newOrder: any;
            let strss = [];
            if (state.objChild.singleValueStr) {
              newOrder = this.quchong(state.objChild.singleValueStr);
      
              newOrder.map((temp, i) => {
                let its = Object.values(temp);
                let newIts = its.toString().replace(/,/g, " ");
                strss.push(newIts);
                return temp;
              });
            }
      
            console.log("888--strss", strss);
            let newOrderStr = strss.toString();
            let sessionParam = JSON.parse(
              window.sessionStorage.getItem("electronParams")
            );
            */
            //获取组件排序值
            //  const newOrderStr = this.rowRef.current.getOrderStr();
            // console.log("888--newOrderStr", newOrderStr);
            const formDrData = this.rowRef.current.getDrDataResult(); //组件界面的内容,
            console.log("888--formDrData", formDrData);
            // 行动态
            let drData = {
                // dbName: state.dbName,  // 为了模板，去掉，6.21 去掉dbname,前端不再传
                dataList: state.rowSrc2.value,
                dataId: state.yearSel,
                fields: [],
                where: state.conditonStr,
                top: state.top,
                activeTab: state.tab,
                order: "",
                //此处这个参数先注掉，因为加上它后，影响了模板生成，所以这个数据的获取,去后台那边重新拿了
                // fuheCpasHeader: this.gridRef.headerService.headerColumn, //这个是展开后的表头,没有层级的
            };
            drData = { ...drData, ...formDrData }; //合并两对象为一个,formDrData为优先
            let drMaps = this.quchong(state.saveArr);
            // const drMaps: DrcMaps[] = newArr;
            const currentRow = this.gridRef.state.currentRecord.coords.row; // 行号
            const currentGridData = this.gridRef.getCpasTableGrid();
            const data = currentGridData?.data;
            const parentRow = currentRow && data && data.length ? data[currentRow] : null;
            const parentLastStr = parentRow ? parentRow[parentRow.length - 1] : "";
            const parentLastCfg = parentLastStr ? JSON.parse(parentLastStr) : {};
            if (parentLastCfg?.formulaState === "finish") {
                return msgError("当前行已设置过动态公式，请勿重新设置～");
            }
            // 生成定义公式
            const testRowFormula = `Dr(${JSON.stringify(drData)}|||${JSON.stringify(drMaps)})`;
            // 定义公式
            this.gridRef.logicFormulaService.setRowFormula(currentRow, testRowFormula);
            try {
                // 调用公式解析引擎
                // const logicData: IGridData =
                //   await this.gridRef.logicFormulaService.executeLogicFormula();
                const currentGridData = this.gridRef.getCpasTableGrid();
                const logicData = await parseLogicFormulaData("reCalculate", currentGridData);
                if (logicData.ok) {
                    await this.gridRef.reloadTable(logicData.data, null, null, true);
                    //刷新公式@todo迁移后台
                    this.formulaService.refreshAllPolymeric();
                }
                else {
                    console.error(logicData.msg);
                    msgError(logicData.msg);
                }
                //this.formulaService.refreshAllPolymericRow();
                //this.formulaService.refreshAllPolymericColumn();
                // if (this.state.cpasData) {
                //   await this.gridRef.reloadTable(logicData, null, null, true);
                //   //刷新行列公式
                //   this.formulaService.refreshAllPolymericRow();
                //   this.formulaService.refreshAllPolymericColumn();
                // }
            }
            catch (e) {
                console.error(e);
                throw e;
            } // 暂时先注销，定义公式完成后才能执行它
        }
        // 列动态取数
        if (state.titles === "列动态取数") {
            console.log("888--列动态取数-state", state);
            const formDcData = this.colRef.current.getDcDataResult(); //组件界面的内容,
            if (formDcData.fields?.length > 0 && formDcData.fields?.length === 2) {
                //主键字段必须加入
                this.setState({ isRowPop: true });
                return message.open({
                    type: "error",
                    content: "不能保存,需要的列至少选择2个,请重新选择. ",
                    className: "custom-class",
                    style: {
                        marginTop: "20vh",
                        height: "100px",
                    },
                });
            }
            console.log("888--formDrData", formDcData);
            let dcData = {
                // dbName: state.dbName, // 6.21 去掉dbname,前端不再传
                // dbName: "FI-2017-00001",
                dataList: state.selSrc1,
                dataId: state.yearSel
                    ? state.yearSel
                    : (sessionParam && sessionParam?.params.sjnd) || "2017",
                dataId1: state.yearSel
                    ? state.yearSel
                    : (sessionParam && sessionParam?.params.sjnd) || "2017",
                dataId2: state.yearSel
                    ? state.yearSel
                    : (sessionParam && sessionParam?.params.sjnd) || "2017",
                fields: state.columnsData,
                where: formDcData.where,
                order: formDcData.order,
                activeTab: state.tab,
            };
            dcData = { ...dcData, ...formDcData }; //合并两对象为一个,formDrData为优先
            //cpas 表 dev 表关系的建立
            let newArr = this.quchong(state.saveArr);
            const dcMaps = newArr;
            let ary = newArr.map((item, i) => {
                console.log("888---item", item);
                return item;
            });
            console.log("888---state.saveArr", state.saveArr);
            var nary = ary.sort();
            for (var i = 0; i < nary.length - 1; i++) {
                if (nary[i].dataSource0 === nary[i + 1].dataSource0) {
                    // cpasHeader?.map((item: any) => {
                    //   colDevCpasMap.map((ite: any) => {
                    //     if (ite.sourceMap === item.cpasName) {
                    //       item.dataListMap = ite.dataListMap;
                    //     }
                    //     return ite;
                    //   });
                    //   return item;
                    // });
                    // this.setState({
                    //   modifyCpasData: cpasHeader,
                    // });
                }
                else {
                    message.open({
                        type: "warning",
                        content: " 不是同一张表的数据，不能建立关系 ",
                        className: "custom-class",
                        style: {
                            marginTop: "20vh",
                        },
                    });
                    this.setState({
                        isRowPop: true,
                        saveArr: [],
                    });
                }
            }
            // 生成定义公式
            const testColumnFormula = `Dc(${JSON.stringify(dcData)}|||${JSON.stringify(dcMaps)})`;
            const currentColumn = this.gridRef.state.currentRecord.coords.col;
            this.gridRef.logicFormulaService.setColumnFormula(currentColumn, testColumnFormula);
            // 执行公式  logicData 组装在 classes / LogicParse.ts 这个页面中 ；
            // 在这个页面中要调接口，把定义公式这里拿到的参数传进去，反解析成想要的cpas表数据结构
            try {
                const currentGridData = this.gridRef.getCpasTableGrid();
                const logicData = await parseLogicFormulaData("reCalculate", currentGridData);
                await this.gridRef.reloadTable(logicData.data, null, null, true);
                //刷新行列公式
                // this.formulaService.refreshAllPolymericRow();
                //this.formulaService.refreshAllPolymericColumn();
                //刷新公式@todo迁移后台
                this.formulaService.refreshAllPolymeric();
                this.setState({
                    cpasData: logicData,
                });
            }
            catch (e) {
                console.error(e);
                throw e;
            }
        }
        // // 执行公式  logicData 组装在 classes / LogicParse.ts 这个页面中 ；
        // // 在这个页面中要调接口，把定义公式这里拿到的参数传进去，反解析成想要的cpas表数据结构
        // try {
        //   const logicData: IGridData =
        //     await this.gridRef.logicFormulaService.executeLogicFormula();
        //   this.gridRef.reloadTable(logicData);
        // } catch (e) {
        //   console.error(e);
        //   throw e;
        // } // 暂时先注销，定义公式完成后才能执行它
    }
    //// 新组装的数据再返回给 cpas 表
    handlerReceiveKeywords = (data) => {
        console.log("888--列动态组装数", data);
        this.setState({
            cpasData: data,
        });
    };
    // 取数源设置下拉弹窗用到的方法
    handleOk = () => {
        console.log("888--handleOk", this.state);
        this.setState({
            dbName: window.sessionStorage.electronParams
                ? JSON.parse(window.sessionStorage.electronParams)?.params?.DBName
                : consts.defaultDbName,
        });
        //此处暂时需要if条件写一下，因为单元格弹窗中cpas表有异常，无法正确刷新cpas表数据
        if (this.state.titles === "单元格取数") {
            this.gridRef.dataSource = "reCalculate";
            console.log("重置表格状态为reCalculate");
            // 弹窗关闭
            this.setState({
                isRowPop: false,
            });
            if (this.cellRef.current) {
                this.cellRef.current.isNeedSyncTableData = true;
                const cellGridData = this.cellRef.current.getCurrentCpasTableIGridData();
                this.gridRef.reloadTable(cellGridData);
            }
            //添加一个新的日志方法  this.gridRef.setTableContentChange
            this.gridRef.setTableContentChange(true, {
                type: "单元格取数操作",
                params: { cpasData: this.state.cpasData },
            });
        }
        else {
            // 弹窗关闭
            this.setState({
                isRowPop: false,
            });
            if (this.cellRef.current) {
                this.cellRef.current.isNeedSyncTableData = true;
            }
        }
        //cpas 表 dev 表关系的建立,还要判断关系不能为空，
        if (this.state.titles === "行动态取数" ||
            this.state.titles === "列动态取数") {
            if (this.state.saveArr.length > 0) {
                console.log("888--saveArr 存在,执行定义公式");
                // 执行定义公式方法
                this.generateLogicFormula(this.state);
            }
            else {
                message.open({
                    type: "warning",
                    content: "两表关系不能为空，否则请点击‘取消’操作",
                    className: "custom-class",
                    style: {
                        marginTop: "20vh",
                    },
                });
                this.setState({
                    isRowPop: true,
                });
            }
        }
        //点确定后要根据所插入的行列位置检查是否有公式,有公式就执行重算，没有公式就新增
        const currentRecord = this.gridRef.state.currentRecord;
        if (!currentRecord) {
            return;
        }
        const { row, col } = currentRecord.coords;
        console.log("888---row--col--handelok", row, col);
        //点确定，先执行一下重算 reCalculateFormula 得需要判断有没有公式，如果有公式就执行重算，如果所点击的行列没有公式就不需要执行重算
        // this.gridRef.reCalculateFormula();
        //列动态确定执行重算的处理
        if (row === -1) {
            let headers = this.state.cpasData.header;
            let formula = headers[col]?.config.formula;
            if (formula) {
                this.gridRef.reCalculateFormula(); // 执行重算
                //有公式，就是编辑;无公式，就是新增  // 添加日志方法
                this.gridRef.setTableContentChange(true, {
                    type: "列动态编辑",
                    params: {
                        saveArr: this.state.saveArr,
                        cpasData: this.state.cpasData,
                    },
                });
            }
            else {
                console.log("888--动态行无公式就新增");
                // 添加日志方法
                this.gridRef.setTableContentChange(true, {
                    type: "列动态新增",
                    params: {
                        saveArr: this.state.saveArr,
                        cpasData: this.state.cpasData,
                    },
                });
            }
        }
        //行动态确定执行重算的处理
        if (row >= 0) {
            let datas = this.state.cpasData.data;
            let item = datas[row];
            let config = JSON.parse(item[item.length - 1]);
            if (config && config.formula) {
                this.gridRef.reCalculateFormula(); // 执行重算
                // 添加日志方法
                this.gridRef.setTableContentChange(true, {
                    type: "行动态编辑",
                    params: {
                        saveArr: this.state.saveArr,
                        cpasData: this.state.cpasData,
                    },
                });
            }
            else {
                // 添加日志方法
                this.gridRef.setTableContentChange(true, {
                    type: "行动态新增",
                    params: {
                        saveArr: this.state.saveArr,
                        cpasData: this.state.cpasData,
                    },
                });
            }
        }
        // // 执行定义公式方法
        // this.generateLogicFormula(this.state);
    };
    handleCancel = () => {
        if (this.state.titles === "单元格取数") {
            if (this.cellRef.current) {
                // 重置控制单元格取数是否需要重新同步底表数据逻辑.
                this.cellRef.current.isNeedSyncTableData = true;
            }
        }
        this.setState({
            isRowPop: false,
        });
        // TODO mxh 逻辑
        // if (this.state.titles === "单元格取数") {
        //   this.setState(
        //     {
        //       cellTabsActiveKey: consts.ReportTabKey,
        //       isRowPop: false,
        //     },
        //     () => {
        //       console.log("888---this.cellRef", this.cellRef.current);
        //       // this.cellRef.current.AccountTabsClick(consts.ReportTabKey);
        //     }
        //   );
        //   if (this.cellRef.current) {
        //     this.cellRef.current.currentMainCpasData = null;
        //   }
        // } else {
        //   // 弹窗关闭
        //   this.setState({
        //     isRowPop: false,
        //   });
        // }
    };
    handleArrowClick(direction) {
        const sliderWidth = this.tableToolsRef.current.clientWidth;
        const scrollWidth = this.tableToolsRef.current.scrollWidth;
        if (direction === "prev") {
            this.setState({
                sliderPosition: 0,
            });
        }
        else {
            this.setState({
                sliderPosition: sliderWidth - scrollWidth - 20,
            });
        }
    }
    draggleRef = React.createRef();
    onStart = (_event, uiData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = this.draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        this.setState({
            bounds: {
                left: -targetRect.left + uiData.x,
                right: clientWidth - (targetRect.right - uiData.x),
                top: -targetRect.top + uiData.y,
                bottom: clientHeight - (targetRect.bottom - uiData.y),
            },
        });
    };
    render() {
        return (_jsxs("div", { className: "handson-tools", children: [_jsx(DevDefaultPopup.Input, { ref: this.batchInsertPopup }), _jsx(DevNotify.Style, { ref: this.menuToolNotifyRef }), _jsx(HandsonTabHeader, { _this: this, className: "handson-header" }), _jsxs("div", { className: "handson-tab-content", children: [this.gridRef.props.type !== "zl" ? (this.state.selectedIndex === 0 ? (this.tableDesignToolsRender()) : (_jsx(GetDataAndValidator, { _this: this }))) : (_jsx(ReductionEditor, { _this: this, className: "", ref: this.reductionEditorRef })), this.gridRef.state.isShowFormulaToolBar && (_jsxs("div", { className: "formula-container", children: [_jsxs("div", { className: "cpas-formula-content", children: [_jsx("div", { className: "cpas-formula-span", children: _jsx("span", { children: "fx(\u8FD0\u7B97\u516C\u5F0F):" }) }), _jsx("div", { style: { flex: 1 }, children: _jsx(Autocomplete, { showClearButton: true, dataSource: this.operationalFormulaOptions, value: this.state.currentOperationalFormula, onValueChanged: this.operationalFormulaChanged, onChange: (e) => {
                                                    this.formulaChanged(e, "o");
                                                }, width: "100%", 
                                                // opened={true}
                                                searchMode: "contains", placeholder: "\u8BF7\u8F93\u5165\u8FD0\u7B97\u516C\u5F0F" }) })] }), _jsxs("div", { className: "cpas-formula-content", children: [_jsx("div", { className: "cpas-formula-span", children: _jsx("span", { children: "fx(\u6821\u9A8C\u516C\u5F0F):" }) }), _jsx("div", { style: { flex: 1 }, children: _jsx(Autocomplete, { width: "100%", showClearButton: true, dataSource: this.operationalFormulaOptions, value: this.state.currentVerifyFormula, onValueChanged: this.verifyFormulaChanged, onChange: (e) => {
                                                    this.formulaChanged(e, "v");
                                                }, placeholder: "\u8BF7\u8F93\u5165\u6821\u9A8C\u516C\u5F0F" }) })] })] }))] }), _jsx(Modal, { title: "设置分组", visible: this.state.isOpenSetGroup, onOk: () => {
                        this.generateGroup();
                        this.setState({
                            isOpenSetGroup: false,
                        });
                    }, onCancel: () => {
                        this.setState({
                            isOpenSetGroup: false,
                        });
                    }, children: _jsxs("div", { children: [_jsx("span", { children: "\u9009\u62E9\u8981\u5206\u7EC4\u7684\u5173\u952E\u5B57\u6BB5" }), _jsx(Select, { placeholder: "\u8BF7\u9009\u62E9\u5173\u952E\u5B57\u6BB5", style: { width: "200px" }, value: this.state.currentGroupKeyColumn, onChange: this.currentGroupKeyColumnChange, children: this.state.keyword.map((item) => {
                                    const column = item["item"];
                                    return (_jsx("option", { value: item.index, children: column.label }, column.key));
                                }) })] }) }), _jsxs(Modal
                // title={this.state.titles}
                , { 
                    // title={this.state.titles}
                    className: "modal_sty", open: this.state.isRowPop, onOk: this.handleOk, onCancel: this.handleCancel, width: "1200px", okText: "\u786E\u8BA4", cancelText: "\u53D6\u6D88", bodyStyle: { padding: 10 }, style: { top: 10 }, modalRender: (modal) => (_jsx(Draggable, { disabled: this.state.disabled, bounds: this.state.bounds, onStart: (event, uiData) => this.onStart(event, uiData), children: _jsx("div", { ref: this.draggleRef, children: modal }) })), title: _jsx("div", { style: {
                            width: "100%",
                            cursor: "move",
                        }, onMouseOver: () => {
                            if (this.state.disabled) {
                                this.setState({
                                    disabled: false,
                                });
                            }
                        }, onMouseOut: () => {
                            this.setState({
                                disabled: true,
                            });
                        }, onFocus: () => { }, onBlur: () => { }, children: this.state.titles }), maskClosable: false, children: [!this.state.isRow ? ("") : (_jsx(RowData, { ref: this.rowRef, getComDataSoureSelect: this.state.ComDataSoureSelect, getDiGaoSourceSelect: this.state.digaoNameSelect, listData: this.state.listData, cpasData: this.state.cpasData, saveArr: this.state.saveArr, getTraslates: this.getTraslate, getWheres: this.getWhere, oneHeaders: [], coords: this.gridRef?.state?.currentRecord?.coords, reviewCpasMap: this.rowTableTraslation, getrowSrc2: this.state.rowSrc2, getrowSrc2event: this.getrowSrc2event, getYearVal: this.getYearVal, yearSel: this.state.yearSel, itemName: this.state.itemName, getTop: this.getTop, activeTab: this.activeTab, tab: this.state.tab, getConditions: this.getConditions, conditonStr: this.state.conditonStr, existsRowFormula: this.state.existsRowFormula, isShowForm: this.state.isShowForm, setIsShowForm: this.setIsShowForm })), !this.state.isCol ? ("") : (_jsx(ColData, { ref: this.colRef, cpasRef: this.gridRef, listData: this.state.listData, cpasData: this.state.cpasData, saveArr: this.state.saveArr, getTraslates: this.getTraslate, coords: this.gridRef?.state?.currentRecord?.coords, onReceiveKeywords: this.handlerReceiveKeywords, getComDataSoureSelect: this.state.ComDataSoureSelect, getDiGaoSourceSelect: this.state.digaoNameSelect, reviewCpasMap: this.twoTableTraslation, getYearVal: this.getYearVal, yearSel: this.state.yearSel, activeIndex: 0, getDsrc1: this.getDsrc1, selSrc1: this.state.selSrc1, getcolums: this.getcolums, itemName: this.state.itemName, activeTab: this.activeTab, tab: this.state.tab, getYearSel1: this.getYearSel1, yearSel1: this.state.yearSel1, getYearSel2: this.getYearSel2, yearSel2: this.state.yearSel2, getTbname1: this.getTbname1, tbName1: this.state.tbName1, getTbname2: this.getTbname2, tbName2: this.state.tbName2, getProjectName1: this.getProjectName1, projectName1: this.state.projectName1, getProjectName2: this.getProjectName2, projectName2: this.state.projectName2, existsColFormula: this.state.existsColFormula, isShowColForm: this.state.isShowColForm, setIsShowColForm: this.setIsShowColForm })), !this.state.isCell ? ("") : (_jsx(CellDataV2, { menuToolRef: this, ref: this.cellRef, itemName: this.gridRef.props.itemName })
                        // <CellData
                        //   isShow={this.state.isRowPop}
                        //   ref={this.cellRef}
                        //   cpasRef={this.gridRef}
                        //   listData={this.state.listData}
                        //   cpasData={this.state.cpasData}
                        //   getComDataSoureSelect={this.state.ComDataSoureSelect}
                        //   getDiGaoSourceSelect={this.state.digaoNameSelect}
                        //   oneHeaders={[]}
                        //   tabText1={""}
                        //   activeIndex3={0}
                        //   onReceiveKeywords={""}
                        //   defLabel={""}
                        //   selVal={""}
                        //   getCoord={this.getCoords}
                        //   cellCoords={this.state.cellCoords}
                        //   colIndex={0}
                        //   getYearVal={this.getYearVal}
                        //   itemName={this.state.itemName}
                        //   menuToolRef={this}
                        //   //
                        //   activeTab1={this.activeTab1}
                        //   tab1={this.state.tab1}
                        //   activeTab2={this.activeTab2}
                        //   tab2={this.state.tab2}
                        //   getYearSel1={this.getYearSel1}
                        //   yearSel1={this.state.yearSel1}
                        //   getYearSel2={this.getYearSel2}
                        //   yearSel2={this.state.yearSel2}
                        //   getTbname1={this.getTbname1}
                        //   tbName1={this.state.tbName1}
                        //   getTbname2={this.getTbname2}
                        //   tbName2={this.state.tbName2}
                        //   getProjectName1={this.getProjectName1}
                        //   projectName1={this.state.projectName1}
                        //   getProjectName2={this.getProjectName2}
                        //   projectName2={this.state.projectName2}
                        //   getDigaoName={this.getDigaoName}
                        //   reportItem={this.state.reportItem}
                        // ></CellData>
                        )] }), _jsx(LogicPopup, { ref: this.draftPopupRef })] }));
    }
}
